package com.itheima.health.common;

import com.itheima.health.util.QiniuUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Set;

/**
 * @author ：xing
 * @date ：Created in 2022年06月07日
 * @description ：
 * @version: 1.0
 */
@Component
@Slf4j
public class ClearImgJob {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private QiniuUtils qiniuUtils;

    private static final Long MIN_DELETE_WAIT_TIME = 5 * 60 * 1000L;

    @Scheduled(cron = "0 3 14 * * ?")//每天的1：10：30执行一次
    public void clearImg() {
        log.info("进入定时任务ClearImgJob:");
        Set<String> difference = redisTemplate.opsForSet().difference(RedisConstant.SETMEAL_PIC_RESOURCES, RedisConstant.SETMEAL_PIC_DB_RESOURCES);

        if (difference != null) {
            for (String picName : difference) {

                Long picNameCreateTime = Long.valueOf(picName.split("_", 2)[0]);
//                时间判断，防止误删在用户图片
                if (System.currentTimeMillis() - picNameCreateTime > MIN_DELETE_WAIT_TIME) {
                    log.info("从七牛云删除垃圾图片");
//                从七牛云删除垃圾图片
                    qiniuUtils.deleteFileFromQiniu(picName);
//                从redis删除垃圾图片
                    log.info("从redis删除垃圾图片");
                    redisTemplate.opsForSet().remove(RedisConstant.SETMEAL_PIC_RESOURCES, picName);
                }

            }
        }

    }
}
